package com.kancy.okhttp.client.log;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.kancy.okhttp.client.support.ApplicationContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * HttpMongoLogbackAppender
 * <p>
 *
 * @author: kancy
 * @date: 2020/3/6 23:31
 **/
public class HttpMongoLogbackAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {

    private static Logger log = LoggerFactory.getLogger(HttpMongoLogbackAppender.class);

    /**
     * 写日志到mongo
     * @param eventObject
     */
    @Override
    protected void append(ILoggingEvent eventObject) {
        try {
            HttpRequestLogRepository logRepository = getHttpRequestLogRepository();
            if (Objects.nonNull(logRepository)){
                HttpRequestLog httpRequestLog = JSON.parseObject(eventObject.getFormattedMessage(),new TypeReference<HttpRequestLog>(){});
                httpRequestLog.setId(UUID.randomUUID().toString());
                httpRequestLog.setLogLevel(eventObject.getLevel().levelStr);
                httpRequestLog.setCreateTime(LocalDateTime.now());
                logRepository.save(httpRequestLog);
            }
        } catch (Exception e) {
            log.error("Unable to save log in appender [{}] , An error occurred ：{}", getName(), e.getMessage());
        }
    }

    /**
     * 获取HttpRequestLogRepository
     * @return
     */
    private HttpRequestLogRepository getHttpRequestLogRepository() {
        HttpRequestLogRepository logRepository = null;
        try {
            logRepository = ApplicationContextHolder.getApplicationContext()
                    .getBean(HttpRequestLogRepositoryImpl.class);
        } catch (Exception e) {
            // ignore
        }
        return logRepository;
    }
}
